package com.autoagent.ai_live_master.scriptRecommendation.service.impl;

import com.autoagent.ai_live_master.common.base.UserContext;
import com.autoagent.ai_live_master.common.utils.BeanConverter;
import com.autoagent.ai_live_master.scriptRecommendation.dto.ScriptConfigDTO;
import com.autoagent.ai_live_master.scriptRecommendation.entity.ScriptConfig;
import com.autoagent.ai_live_master.scriptRecommendation.mapper.ScriptConfigMapper;
import com.autoagent.ai_live_master.scriptRecommendation.service.ScriptConfigService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 话术生成核心配置表 服务实现类
 * </p>
 *
 * @author TraeAI
 * @since 2024-07-26
 */
@Service
@Slf4j
public class ScriptConfigServiceImpl extends ServiceImpl<ScriptConfigMapper, ScriptConfig> implements ScriptConfigService {


    @Override
    public List<ScriptConfigDTO> getAllScriptConfigs() {
        Long userId= UserContext.getCurrentUserId();
        log.info("开始获取用户话术配置列表, 用户ID: {}", userId);
        try {
            List<ScriptConfig> scriptConfigs = list(new QueryWrapper<ScriptConfig>().eq("user_id", userId));
            List<ScriptConfigDTO> result = scriptConfigs.stream()
                    .map(config -> BeanConverter.convert(config, ScriptConfigDTO.class))
                    .collect(Collectors.toList());
            log.info("获取用户话术配置列表成功, 用户ID: {}, 获取到{}条记录", userId, result.size());
            return result;
        } catch (Exception e) {
            log.error("获取用户话术配置列表失败, 用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            throw new RuntimeException("获取用户话术配置列表失败", e);
        }
    }

    @Override
    public Page<ScriptConfigDTO> getPageByUserId(Long userId, Integer pageNum, Integer pageSize, String keyword) {
        log.info("分页获取用户的话术配置列表 - 用户ID: {}, 页码: {}, 每页大小: {}, 关键字: {}", userId, pageNum, pageSize, keyword);

        Page<ScriptConfig> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ScriptConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ScriptConfig::getUserId, userId);

        // 如果有关键字，添加configName字段的模糊匹配
        if (keyword != null && !keyword.trim().isEmpty()) {
            wrapper.like(ScriptConfig::getConfigName, keyword.trim());
        }

        // 按创建时间倒序排列
        wrapper.orderByDesc(ScriptConfig::getCreatedAt);

        Page<ScriptConfig> entityPage = this.page(page, wrapper);

        // 转换为DTO分页对象
        Page<ScriptConfigDTO> dtoPage = new Page<>();
        dtoPage.setTotal(entityPage.getTotal());
        dtoPage.setCurrent(entityPage.getCurrent());
        dtoPage.setSize(entityPage.getSize());
        List<ScriptConfigDTO> dtoList = entityPage.getRecords().stream()
                .map(entity -> BeanConverter.convert(entity, ScriptConfigDTO.class))
                .collect(Collectors.toList());

//        dtoList.forEach(dto -> log.info("脚本配置DTO内容: {}", dto));  // 打印每个DTO内容
        dtoPage.setRecords(dtoList);
        return dtoPage;
    }

    @Override
    @Transactional
    public ScriptConfigDTO createScriptConfig(ScriptConfig scriptConfig) {
        log.info("开始创建话术配置, 用户ID: {}, 配置名称: {}", scriptConfig.getUserId(), scriptConfig.getConfigName());
        try {
            save(scriptConfig);
            ScriptConfigDTO result = BeanConverter.convert(scriptConfig, ScriptConfigDTO.class);
            log.info("创建话术配置成功, ID: {}, 用户ID: {}", scriptConfig.getId(), scriptConfig.getUserId());
            return result;
        } catch (Exception e) {
            log.error("创建话术配置失败, 用户ID: {}, 配置名称: {}, 错误: {}", scriptConfig.getUserId(), scriptConfig.getConfigName(), e.getMessage(), e);
            throw new RuntimeException("创建话术配置失败", e);
        }
    }


    @Override
    @Transactional
    public ScriptConfigDTO updateScriptConfig(ScriptConfig scriptConfig) {
        log.info("开始更新话术配置, ID: {}, 用户ID: {}", scriptConfig.getId(), scriptConfig.getUserId());
        try {
            // 先检查记录是否存在
            ScriptConfig existingConfig = getById(scriptConfig.getId());
            if (existingConfig == null) {
                log.warn("更新话术配置失败, 记录不存在, ID: {}", scriptConfig.getId());
                throw new RuntimeException("话术配置不存在");
            }

            boolean updated = updateById(scriptConfig);
            if (!updated) {
                log.warn("更新话术配置失败, ID: {}", scriptConfig.getId());
                throw new RuntimeException("更新话术配置失败");
            }
            ScriptConfigDTO result = BeanConverter.convert(getById(scriptConfig.getId()), ScriptConfigDTO.class);
            log.info("更新话术配置成功, ID: {}, 用户ID: {}", scriptConfig.getId(), scriptConfig.getUserId());
            return result;
        } catch (Exception e) {
            log.error("更新话术配置失败, ID: {}, 用户ID: {}, 错误: {}", scriptConfig.getId(), scriptConfig.getUserId(), e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    @Override
    @Transactional
    public boolean deleteScriptConfig(Integer id) {
        log.info("开始删除话术配置, ID: {}", id);
        try {
            // 先检查记录是否存在
            ScriptConfig existingConfig = getById(id);
            if (existingConfig == null) {
                log.warn("删除话术配置失败, 记录不存在, ID: {}", id);
                throw new RuntimeException("话术配置不存在");
            }
            
            boolean removed = removeById(id);
            if (!removed) {
                log.warn("删除话术配置失败, ID: {}", id);
                throw new RuntimeException("删除话术配置失败");
            }
            log.info("删除话术配置成功, ID: {}, 用户ID: {}", id, existingConfig.getUserId());
            return true;
        } catch (Exception e) {
            log.error("删除话术配置失败, ID: {}, 错误: {}", id, e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}